#! /usr/bin/env python
# coding=utf-8

# 批量运行 aaml
ctlpath = 'aaml.ctl'

work_file = 'tmpsh'


import shutil

import os
import threading

import sys
import argparse


parser = argparse.ArgumentParser(
    description=''' 对运行完 conver02_prepare_paml01.py 的 准备好的文件 生成一个多线程运行aaml的sh 并运行
    用法:
    conver02_run_paml01.py  -a /home/NAS1/c3/assemble/tools/paml4.9j/bin/codeml -i OGS_for_testing -t 64
    由大天才于2021年7月19日创建于浙江农业大学''')



parser.add_argument('-a',
                help='必须给定，codeml脚本的路径')



parser.add_argument('-i',
                help='必须给定，工作路径')

parser.add_argument('-t',
                help='并行核数 默认为8')


args = parser.parse_args()

try:
	shutil.rmtree(work_file)
except:
	pass
try:
	os.mkdir(work_file)
except:
	pass


if not args.i or not args.a:
    parser.print_help()
    sys.exit()


infile = args.i

ppath = args.a
if not args.t:
	thread = 8
else:
	thread = int(args.t)


# thread = 5
# infile = r'test'
# ppath = r'/home/good/tools/paml4.9j/bin/codeml'




thread_dic = {i:[] for i in range(0,thread)}

n = 0
for i in os.listdir(infile):
	if os.path.isdir(infile+'/'+i):
		thread_dic[n%thread].append(i)
		n+=1

cwd = os.getcwd()

for i in thread_dic:

	outfile = open(work_file+'/'+str(i)+'.sh','w')

	for j in thread_dic[i]:
		outfile.write('cd '+infile+'/'+j+'\n')
		outfile.write(ppath + ' '+ctlpath+'\n')
		outfile.write('cd '+cwd +'\n')
	outfile.close()



def run_func(file_path):


	a = os.system('sh '+file_path)


	return	None

n = 0
thread_pool = []
for i in thread_dic:

	file_path = work_file+'/'+str(i)+'.sh'

	n += 1

	th = threading.Thread(target=run_func, args=[file_path], name='th_'+str(n))
	thread_pool.append(th)


for i in range(thread):
	if len(thread_pool)>i:
		thread_pool[i].start()

